import { type FC } from 'react'
import {
  Routes,
  Route,
  Navigate,
} from 'react-router-dom'
import {
  NotFound,
  AuthRouter,
} from '@/library/widgets'
import { routesItemLists } from './custom-config'
import { type IRoutesItemLists } from './baseType'
import { generateRouteIndexPath } from './tools'

const routesLists = generateRouteIndexPath(routesItemLists)

const renderRoutes = (itemLists: IRoutesItemLists) => {
  if (itemLists && itemLists.length) {
    return itemLists.map(({
      auth = false,
      path,
      component: Component,
      index = false,
      children,
      redirect,
    }) => (
      children && children.length ? (
        <Route
          path={path}
          key={path}
          element={<AuthRouter auth={auth}>{Component}</AuthRouter>}
        >
          {renderRoutes(children)}
        </Route>
      ) : (
        <Route
          path={index ? undefined : path}
          key={path}
          index={index}
          element={redirect ? (<Navigate to={redirect} />) : (<AuthRouter auth={auth}>{Component}</AuthRouter>)}
        />
      )
    ))
  }
  return null
}

const Router: FC = () => (
  <Routes>
    {renderRoutes(routesLists)}
    <Route path="/*" element={<NotFound />} />
  </Routes>
)

export default Router
